import cn.hutool.poi.word.TableUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.*;

import org.example.utils.Word2PdfAsposeUtil;
import org.junit.Test;

public class ExportPdf {
    private final List<String> tableFields = Arrays.asList("a", "b", "c", "d", "e");

    @Test
    public void export() throws IOException, InvalidFormatException {
        String path = "/Users/nopepper/study/code/Demo/project/src/main/resources/file/";
        String docPath = "a.docx";
        String docOutPath = "a_out.pdf";
        String picPath = "pic.jpg";
        //获取表格中的数据
        List<Map<String, String>> tableResult = getTableData();
        //获取关键字数据
        Map<String, String> keywordResult = getKeyData();
        //获取图片
        InputStream signaturePicture = new FileInputStream(path + picPath);

        // 加载Word文档
        InputStream templateWord = new FileInputStream(path + docPath);
        XWPFDocument document = new XWPFDocument(templateWord);


        //操作表格
        List<XWPFTable> tables = document.getTables();
        //替换表格关键字
        tables.get(0).getRows().forEach(row -> {
            List<XWPFTableCell> cells = row.getTableCells();
            cells.forEach(cell -> {
                XWPFRun run = cell.getParagraphs().get(0).getRuns().get(0);
                keywordResult.forEach((k, v) -> {
                    if (k.equals(run.getText(0))) {
                        run.setText(v, 0);
                    }
                });
            });
        });

        //替换段落关键字
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        paragraphs.forEach(paragraph -> {
            paragraph.getRuns().forEach(run -> {
                keywordResult.forEach((k, v) -> {
                    if (k.equals(run.getText(0))) {
                        run.setText(v, 0);
                    }
                });
            });
        });

        //添加表格数据
        for (int i = 0; i < tableResult.size(); i++) {
            Map<String, String> objectMap = tableResult.get(i);
            XWPFTableRow row = tables.get(0).insertNewTableRow(i + 1);
            for (int j = 0; j < tableFields.size(); j++) {
                XWPFTableCell cell = TableUtil.getOrCreateCell(row, j);
                cell.setText(objectMap.get(tableFields.get(j)));
            }
        }

        //替换图片
        paragraphs.forEach(paragraph -> {
            paragraph.getRuns().forEach(run -> {
                if ("#pic".equals(run.getText(0))) {
                    try {
                        run.addPicture(signaturePicture, XWPFDocument.PICTURE_TYPE_JPEG, "inserted.jpg",
                                Units.toEMU(100), Units.toEMU(100));
                        run.setText("",0);
                    } catch (InvalidFormatException | IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        });



        //输出
        document.write(new FileOutputStream(path + "a_out.docx"));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.write(outputStream);
        Word2PdfAsposeUtil.doc2pdf(new ByteArrayInputStream(outputStream.toByteArray()), path + docOutPath);
        //输出
//        document.write();
    }

    private Map<String, String> getKeyData() {
        Map<String, String> map = new HashMap<>();
        map.put("$a", "测试a");
        map.put("$b", "测试b");
        map.put("$c", "测试c");
        map.put("$d", "测试d");
        return map;
    }

    private List<Map<String, String>> getTableData() {
        Random random = new Random();
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String, String> map = new HashMap<>();
            tableFields.forEach(a -> {
                map.put(a, String.valueOf(random.nextInt(10)));
            });
            list.add(map);
        }
        return list;
    }


    public static void main(String[] args) {
        String filePath = "file/a.txt";
//        URL resourceUrl = getClass().getClassLoader().getResource(filePath);
//        String resourcePath = resourceUrl.getPath();
        System.out.println(ExportPdf.class.getClassLoader().getResource(""));

    }
}
